
#include "qlogger_.hpp"
#include "qloggerengine.hpp"
#include "qloggerappender.hpp"

QLogger::QLogger (QString moduleName, QObject *parent):QObject(parent)
{
    name = moduleName;
}

QLogger::~QLogger()
{

}

void QLogger::addAppender(QLoggerAppender *appender)
{
    QSharedPointer<QLoggerAppender> res = QLoggerEngine::handle().appender(appender);
    if ( !res.isNull())
        {
            appenders_ << res;
        }
}

void QLogger::delAppender(QLoggerAppender *appender)
{
    auto er = std::find_if(appenders_.begin(),appenders_.end(),[appender](QSharedPointer<QLoggerAppender>& a){ return (a.data() == appender);});
    if(er != appenders_.end())
        appenders_.erase(er);
}

bool QLogger::isEventAccepted (QLoggerAppender *appender, const QLoggerEvent &event)
{
    if (!(appender->level() & event.level))
       return false;
    return true;
}

QLogger& QLogger::debug(const QString &message, const char *file , int line, const char* func)
{
    this->log(LevelDebug, message, file, line, func);
    return (*this);
}

QLogger& QLogger::info(const QString &message, const char *file , int line, const char* func)
{
    this->log(LevelInfo, message, file, line, func);
    return (*this);
}

QLogger& QLogger::warn(const QString &message, const char *file , int line, const char* func)
{
    this->log(LevelWarn, message, file, line, func);
    return (*this);
}

QLogger& QLogger::error(const QString &message, const char *file , int line, const char* func)
{
    this->log(LevelError, message, file, line, func);
    return (*this);
}

QLogger& QLogger::fatal(const QString &message, const char *file , int line, const char* func)
{
    this->log(LevelFatal, message, file, line, func);
    return (*this);
}

QLogger& QLogger::critical(const QString &message, const char *file , int line, const char* func)
{
    this->log(LevelCritical, message, file, line, func);
    return (*this);
}

QLogger& QLogger::exception(const QString &message, const char *file , int line, const char* func)
{
    this->log(LevelException, message, file, line, func);
    return (*this);
}

void QLogger::log(QLoggerLevel level, const QString& message,
                  const char* file, int line, const char* func)
{
    QLoggerEvent event;
    event.dateTime = QDateTime::currentDateTime();
    event.logger   = this;
    event.level    = level;
    event.message  = &message;
    event.file     = file;
    event.line     = line;
    event.func     = func;

    log(event);
}

void QLogger::log(QLoggerEvent& event)
{
    foreach (const QSharedPointer<QLoggerAppender>& appender, appenders_)
        {
            if (isEventAccepted(appender.data(), event) == true)
                appender->write(event);
        }
}

